from __future__ import annotations
import sys


class Options:
    def __init__(self):
        self.dts_out = "dts_out"  # 默认
        self.index_ts: str | None = None
        self.disable_const_enum = False
        self.enable_clone = False
        self.enable_json = False
        self.enable_namespace = False
        self.enable_arena_switch = False
        self.help = False

    @staticmethod
    def dump_help():
        sys.stderr.write(
            """
usage:
    protoc --napi_out=<OUT_DIR> [--napi_opt=dts_out=./dts_out] ...
options:
    help: dump this message
    dts_out: .d.ts output path, default is dts_out
    disable_const_enum: disable const enum generation
    enable_clone: enable clone function generation
    enable_json: enable toJsonString function generation
    enable_namespace: enable namespace generation in .d.ts
    enable_arena_switch: enable arena switch function generation in .d.ts
    index_ts: index.ts path, do not generate by default, ignored if enable_namespace is set
"""
        )


def parse_options(parameter: str | None) -> Options:
    opts = Options()
    if not parameter:
        return opts

    # 简单解析 key=value 列表
    for item in parameter.split(","):
        if item in ["help", "?"]:
            Options.dump_help()
            opts.help = True
            return opts
        if "=" not in item:
            if item == "disable_const_enum":
                opts.disable_const_enum = True
            elif item == "enable_clone":
                opts.enable_clone = True
            elif item == "enable_json":
                opts.enable_json = True
            elif item == "enable_namespace":
                opts.enable_namespace = True
            elif item == "enable_arena_switch":
                opts.enable_arena_switch = True
            continue
        key, val = item.split("=", 1)
        if key == "dts_out":
            opts.dts_out = val
        elif key == "index_ts":
            opts.index_ts = val
        else:
            print(f"ignored unknown option: {key}", file=sys.stderr)
    return opts
